use serde::{Deserialize, Serialize};
use std::net::IpAddr;
use std::time::Duration;
use tokio::time;
use toml;
use std::fs;
use std::error::Error;
use chrono::Local;
use std::path::PathBuf;
use std::process;

const DEFAULT_CONFIG: &str = r#"[server]
url = "http://localhost:5000"  # 修改为你的服务器地址
interval = 300  # 发送间隔(秒)，默认5分钟

[auth]
token = "your-secret-token-here"  # 替换为你的认证令牌
"#;

#[derive(Deserialize)]
struct Config {
    server: ServerConfig,
    auth: AuthConfig,
}

#[derive(Deserialize)]
struct ServerConfig {
    url: String,
    interval: u64,  // 发送间隔(秒)
}

#[derive(Deserialize)]
struct AuthConfig {
    token: String,  // 认证令牌
}

#[derive(Serialize)]
struct IPData {
    ipv4: Vec<String>,
    ipv6: Vec<String>,
    timestamp: String,
}

async fn get_local_ips() -> (Vec<String>, Vec<String>) {
    let mut ipv4s = Vec::new();
    let mut ipv6s = Vec::new();

    // 获取所有网络接口
    for iface in if_addrs::get_if_addrs().expect("无法获取网络接口") {
        let ip = iface.addr.ip();
        if !ip.is_loopback() {
            match ip {
                IpAddr::V4(ipv4) => ipv4s.push(ipv4.to_string()),
                IpAddr::V6(ipv6) => ipv6s.push(ipv6.to_string()),
            }
        }
    }

    (ipv4s, ipv6s)
}

async fn send_ip_data(config: &Config) -> Result<(), Box<dyn Error>> {
    let client = reqwest::Client::new();
    let (ipv4s, ipv6s) = get_local_ips().await;
    
    let timestamp = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    let ip_data = IPData {
        ipv4: ipv4s.clone(),
        ipv6: ipv6s.clone(),
        timestamp: timestamp.clone(),
    };

    let url = format!("{}/api/get_ip", config.server.url);
    let response = client
        .post(&url)
        .header("X-API-Token", &config.auth.token)
        .json(&ip_data)
        .send()
        .await?;

    let status = response.status();
    if !status.is_success() {
        let error_text = response.text().await?;
        return Err(format!("服务器响应错误: {} - {}", status, error_text).into());
    }

    println!("[{}] IP数据已发送 (IPv4: {}, IPv6: {})", 
        timestamp,
        ipv4s.len(),
        ipv6s.len()
    );
    Ok(())
}

fn get_config_path() -> PathBuf {
    // 始终使用当前工作目录下的 config.toml 文件
    PathBuf::from("config.toml")
}

fn ensure_config_exists(config_path: &PathBuf) -> Result<bool, Box<dyn Error>> {
    if !config_path.exists() {
        println!("未找到配置文件，正在创建默认配置文件: {:?}", config_path);
        fs::write(config_path, DEFAULT_CONFIG)?;
        println!("\n默认配置文件已创建！");
        println!("请编辑配置文件并设置以下内容：");
        println!("1. 修改 server.url 为你的服务器地址");
        println!("2. 设置 auth.token 为你的认证令牌");
        println!("3. 根据需要调整 interval 的值（默认为300秒）");
        println!("\n完成配置后重新运行程序。");
        return Ok(false);
    }
    Ok(true)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let config_path = get_config_path();
    
    // 确保配置文件存在
    if !ensure_config_exists(&config_path)? {
        println!("\n请在编辑完配置文件后重新运行程序。");
        process::exit(0);
    }
    
    let config_str = fs::read_to_string(&config_path)?;
    let config: Config = toml::from_str(&config_str)?;

    println!("IP发送程序已启动 (间隔: {}秒)", config.server.interval);

    // 定时发送
    let mut interval = time::interval(Duration::from_secs(config.server.interval));
    loop {
        if let Err(e) = send_ip_data(&config).await {
            eprintln!("发送失败: {}", e);
        }
        interval.tick().await;
    }
}